package com.youlu.campus.admin.task;

import com.youlu.campus.service.order.OrderService;
import com.youlu.campus.service.pay.PayNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PayNotifyService payNotifyService;
    private final String wechatPayNotifyLock = "wechat.pay.order:notify";

    /**
     * 五分钟执行一次
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void doPayOrderJob() {
        log.info("开始执行");
        Integer hour = 12;
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("order:status", "1", 3L, TimeUnit.MINUTES);
        if (Objects.nonNull(flag) && !flag) {
            return;
        }
        orderService.doOrderStatusJob(hour);
    }

    /**
     * 1分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void doPayStatusOrderJob() {
        log.info(":>>> 开始执行微信支付通知 ");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(wechatPayNotifyLock, "1", 1L, TimeUnit.MINUTES);
        if (Objects.nonNull(flag) && !flag) {
            return;
        }
        payNotifyService.scanPayNotify(new Date());
        redisTemplate.delete(wechatPayNotifyLock);
    }
}
